//
//  FileViewController.swift
//  FileAPIDemo
//
//  Created by David on 16/9/24.
//  Copyright © 2016年 David. All rights reserved.
//  本地文件管理器

import UIKit

class FileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate {
    
    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! // 沙盒路径
    var continuePath:String = ""
    let CREATE_DIR_ALERT_ID = 101
    let DELETE_FILE_ALERT_ID = 102
    
    //var editToolBar: UIToolbar!
    var multiConfirmBtn:UIBarButtonItem!
    var editButton: UIBarButtonItem!
    
    var tableView :UITableView!
    var refreshed = true
    var fileData:NSMutableArray!
    var footer:UILabel!
    var fileToDelete:FFFileItem?
    
    // 下级目录的构造器
    convenience init(path: String){
        self.init()
        continuePath = "/\(path)"
    }
    
    // 类型是否支持
    func matchType(type: String?) -> Bool{
        for match in Fatcat.SUPPORTED_TYPES{
            if type == match {
                return true
            }
        }
        return false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // a bar button to add directory
        //navBarItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(FileViewController.addDir))
        
        let backItem = UIBarButtonItem()
        backItem.title = "返回"
        backItem.tintColor = UIColor.whiteColor()
        navigationItem.backBarButtonItem = backItem
        
        editButton = UIBarButtonItem(title: "多选", style: .Plain, target: self, action: #selector(FileViewController.multiSelect(_:)))
        navigationItem.rightBarButtonItem = editButton
        
        multiConfirmBtn = UIBarButtonItem(title: "上传", style: .Plain, target: self, action: #selector(FileViewController.multiSubmit))
        
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), style: .Grouped)
        view.addSubview(tableView)
        tableView.tintColor = Fatcat.SELECTED_COLOR
        
        fileData = NSMutableArray()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        var dirName = "本地文件"
        if continuePath != "" {
            dirName = continuePath.componentsSeparatedByString("/").last!
        }
        
        title = dirName
        
        footer = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        footer.textAlignment = .Center
        
        footer.textColor = UIColor.lightGrayColor()
        
//        editToolBar = UIToolbar(frame: CGRect(x: 0, y: view.bounds.height - 48, width: view.bounds.width, height: 48))
//        view.addSubview(editToolBar)
//        
//        editToolBar.setItems([multiConfirmBtn], animated: true)
        
        refreshList()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if refreshed{
            refreshed = false
            
        }else{
            print("appear refresh")
            refreshList()
            refreshed = false
        }
    }
    
    func refreshList(){
        let fileMan = NSFileManager.defaultManager()
        //print(DOCUMENT_PATH)
        let lsDir =  try? fileMan.contentsOfDirectoryAtPath("\(DOCUMENT_PATH)\(continuePath)")
        //print(lsDir)
        fileData = NSMutableArray()
        if lsDir != nil {
            
            for item in lsDir! {
                let thisItemDic = NSMutableDictionary()
                var isDir:ObjCBool = false
                // 判断文件类型
                if fileMan.fileExistsAtPath("\(DOCUMENT_PATH)\(continuePath)/\(item)", isDirectory: &isDir) {
                    thisItemDic.setObject(item, forKey: "filename")
                    if isDir {
                        // 文件夹
                        thisItemDic.setObject("dir", forKey: "type")
                        fileData.addObject(thisItemDic)
                    }else{
                        // 判断扩展名，只显示支持的类型
                        let type = item.componentsSeparatedByString(".").last?.lowercaseString
                        if type != nil {
                            if matchType(type) {
                                thisItemDic.setObject(type!, forKey: "type")
                                fileData.addObject(thisItemDic)
                            }
                            
                        }
                        
                    }
                    
                }
                
            }
            tableView.reloadData()
            footer.text = "\(fileData.count)个项目"
        }
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fileData.count
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return 64
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if fileData.count == 0{
            return (view.bounds.width - 32)*1.875
        }
        return 64
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "file")
        
        if fileData.count > 0{
            let thisRowItem = fileData.objectAtIndex(indexPath.row) as! NSDictionary
            
            
            var fileType = ""
            if thisRowItem.objectForKey("type") != nil{
                fileType = thisRowItem.objectForKey("type") as! String
            }
            
            var indent:CGFloat = 0.0
            if tableView.editing {
                indent = 32
            }
            
            let icon = UIImageView(frame: CGRect(x: indent + 16, y: 8, width: 48, height: 48))
            icon.contentMode = .Center
            icon.backgroundColor = UIColor.lightGrayColor()
            cell.addSubview(icon)
            
            let nameLabel = UILabel(frame: CGRect(x: indent + 72, y: 8, width: view.bounds.width - 80, height: 20))
            nameLabel.text = thisRowItem.objectForKey("filename") as? String
            nameLabel.lineBreakMode = .ByTruncatingMiddle
            cell.addSubview(nameLabel)
            
            let subLabel = UILabel(frame: CGRect(x: indent + 72, y: 36, width: view.bounds.width - 80, height: 20))
            
            subLabel.textColor = UIColor.lightGrayColor()
            cell.addSubview(subLabel)
            // MARK: 加图标
            if fileType == "dir" {
                subLabel.text = "文件夹"
                
                // DEL: 显示文件夹中的项目个数
                //            let lsDir =  try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(DOCUMENT_PATH)
                //            if lsDir != nil{
                //                if lsDir!.count == 0{
                //                    cell.detailTextLabel?.text = "空文件夹"
                //                }else{
                //                    cell.detailTextLabel?.text = "\(lsDir!.count)个项目"
                //                }
                //
                //            }
                
                cell.accessoryType = .DisclosureIndicator
                icon.backgroundColor = UIColor.clearColor()
                icon.image = UIImage(named: "documents_icon_folder")
            }else{
                
                subLabel.text = "\(fileType)文件"
                if fileType == "doc" || fileType == "docx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_doc")
                }else if fileType == "xls" || fileType == "xlsx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_xls")
                }else if fileType == "ppt" || fileType == "pptx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_ppt")
                }else if fileType == "pdf"{
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_pdf")
                }else if fileType == "txt"{
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_txt")
                }else if fileType == "png" || fileType == "jpg" || fileType == "jpeg" || fileType == "bmp" {
                    let thisFileDic = fileData.objectAtIndex(indexPath.row) as! NSDictionary
                    let filename = thisFileDic.objectForKey("filename") as! String
                    let filepath = "\(DOCUMENT_PATH)\(continuePath)/\(filename)"
                    icon.contentMode = .ScaleAspectFill
                    icon.layer.masksToBounds = true
                    icon.image = UIImage(contentsOfFile: filepath)
                }
            }
        }else{
//            let imageView = UIImageView(image: UIImage(named: "guide.png", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: nil))
            
            
        }
        
        
        
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if !tableView.editing {
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            if fileData.count > 0{
                hidesBottomBarWhenPushed = true
                let thisFileDic = fileData.objectAtIndex(indexPath.row) as! NSDictionary
                if thisFileDic.objectForKey("type") != nil{
                    let type = thisFileDic.objectForKey("type") as! String
                    let filename = thisFileDic.objectForKey("filename") as! String
                    if type == "dir"{
                        let nextVC = FileViewController(path: filename)
                        navigationController?.pushViewController(nextVC, animated: true)
                    }else if type == "jpg" || type == "jpeg" || type == "png" || type == "bmp"{
                        let filepath = "\(DOCUMENT_PATH)\(continuePath)/\(filename)"
                        
                        navigationController?.pushViewController(ImagePreViewController(named: filename, localImg: UIImage(contentsOfFile: filepath), localFilePath: filepath), animated: true)
                    }else{
                        let filepath = "\(DOCUMENT_PATH)\(continuePath)/\(filename)"
                        navigationController?.pushViewController(FilePreViewController(path: filepath), animated: true)
                    }
                    
                }
            }
            
        }
    }
    
    // DEL: 新建文件夹
    /*
    func addDir(){
        let alert = UIAlertView(title: "新建文件夹", message: nil, delegate: self, cancelButtonTitle: "取消")
        alert.tag = CREATE_DIR_ALERT_ID
        alert.addButtonWithTitle("确定")
        alert.alertViewStyle = .PlainTextInput
        //TODO 加判断，是否已经存在新建文件夹
        alert.textFieldAtIndex(0)?.text = "新建文件夹"
        alert.show()
    }
    */
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        switch alertView.tag {
        case CREATE_DIR_ALERT_ID: // 创建文件夹操作
            if buttonIndex == 1{
                let newDirName = alertView.textFieldAtIndex(0)?.text
                print("new dir \(newDirName)")
                _ = try? NSFileManager.defaultManager().createDirectoryAtPath("\(DOCUMENT_PATH)\(continuePath)/\(newDirName!)", withIntermediateDirectories: true, attributes: nil)
            }
            break
        case DELETE_FILE_ALERT_ID:
            if buttonIndex == 1{
                if fileToDelete != nil{
                    let indexPath = fileToDelete!.indexPathInTable!
                    fileData.removeObjectAtIndex(indexPath.row)
                    
                    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
                    tableView.reloadData()
                    footer.text = "\(fileData.count)个项目"
                    
                    // MARK:WARN: 异常没处理
                    _ = try? NSFileManager.defaultManager().removeItemAtPath((fileToDelete?.path)!)
                    
                    
                }
                
            }
            break
        default:
            break
        }
    }
    
    // 底部文字
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        if fileData.count > 0{
            footer.addSubview(self.footer)
            
        }else{
            footer.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: (view.bounds.width - 32)*1.875)
            let imageView = UIImageView(frame: CGRect(x: 16, y: 0, width: view.bounds.width - 32, height: (view.bounds.width - 32)*1.875))
            imageView.image = UIImage(named: "guide")
            footer.addSubview(imageView)
        }
        return footer
    }

    // 打开编辑
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        if fileData.count > 0{
            let thisFileDic = fileData.objectAtIndex(indexPath.row) as! NSDictionary
            if thisFileDic.objectForKey("type") != nil{
                let type = thisFileDic.objectForKey("type") as! String
                if type != "dir" {
                    return true
                }
            }
        }
        
        return false
    }
    
    //重载默认按钮文字
    func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
        return "删除"
    }
    
    // 删除文件操作 不删文件夹
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        let thisFileItem = fileData.objectAtIndex(indexPath.row) as! NSDictionary
        let thisFileName = thisFileItem.objectForKey("filename") as! String
        let thisFilePath = "\(DOCUMENT_PATH)\(continuePath)/\(thisFileName)"
        let alert = UIAlertView(title: "删除\(thisFileName)?", message: "删除之后不可恢复", delegate: self, cancelButtonTitle: "取消")
        alert.addButtonWithTitle("删除")
        alert.tag = DELETE_FILE_ALERT_ID
        fileToDelete = FFFileItem(path: thisFilePath)
        fileToDelete?.indexPathInTable = indexPath
        alert.show()
        
        
    }
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        if tableView.editing{
            return UITableViewCellEditingStyle(rawValue: UITableViewCellEditingStyle.Delete.rawValue | UITableViewCellEditingStyle.Insert.rawValue)!
        }
        return .Delete
        
    }
    func multiSelect(sender: UIBarButtonItem){
        if tableView.editing {
            sender.title = "多选"
            navigationItem.leftBarButtonItem = nil
            navigationItem.rightBarButtonItem = sender
        }else{
            sender.title = "取消"
            navigationItem.leftBarButtonItem = sender
            navigationItem.rightBarButtonItem = multiConfirmBtn
        }
        tableView.setEditing(!tableView.editing, animated: true)
        tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .None)
    }
    
    func multiSubmit(){
        let selections = tableView.indexPathsForSelectedRows
        if selections != nil {
            if NSUserDefaults.standardUserDefaults().objectForKey("user") == nil {
                presentViewController(UDLoginViewController(), animated: true, completion: nil)
                
            }else{
                if selections!.count > 0 && selections!.count < 9 {
                    var filesToUpload:[UDFile] = []
                    for index in selections!{
                        let file = fileData.objectAtIndex(index.row) as! NSDictionary
                        let fileName = file.objectForKey("filename") as! String
                        let filePath = "\(DOCUMENT_PATH)\(continuePath)/\(fileName)"
                        
                        let sizeToShow = Fatcat.getFileSize(filePath)
                        
                        filesToUpload.append(UDFile(filePath: filePath, fileName: fileName, fileSize: sizeToShow, fileMD5:  nil))
                        
                    }
                    hidesBottomBarWhenPushed = true
                    navigationController?.pushViewController(FileReadyViewController(files: filesToUpload, step0VC: self), animated: true)
                }else{
                    let alert = UIAlertController(title: "最多可以上传9个文件", message: nil, preferredStyle: .Alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
                    presentViewController(alert, animated: true, completion: nil)
                }
                
                
            }
            multiSelect(editButton)
        }else{
            UIAlertView(title: "请选择文件", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class FFFileItem{
    var path:String
    var indexPathInTable:NSIndexPath?
    init(path: String){
        self.path = path
    }
}
